<template>
  <div style="width: 100%; height: 100%">

    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions" @formReset="formResetFn">
      <template #toolbar_buttons>
          <vxe-button type="submit" status="primary" content="查看未入库订单" @click="handleCreate" style="margin-left: 5px;"></vxe-button>
          <vxe-button type="submit" status="primary" content="查看本周新增订单" @click="openTiaoZheng" style="margin-left: 5px;"></vxe-button>
          <vxe-button type="submit" status="success" content="更新forecast" :loading="loading" @click="upForecasFn" style="margin-left: 5px;"></vxe-button>
          <vxe-button type="submit" status="success" content="提交计划" @click="submitBeforeFn" style="margin-left: 5px;" :loading="loading" v-if="formValue.dataSchema=='MTS D'"></vxe-button>
          <vxe-button type="submit" status="primary" content="保存填写" :loading="loading" @click="saveForecastDataFn" style="margin-left: 5px;"></vxe-button>
          <vxe-button type="submit" status="info" content="清空填写" :loading="loading" @click="cleanForecastDataFn" style="margin-left: 5px;"></vxe-button>

      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>


    </vxe-grid>


    <FormModal @register="register" @success="handleSuccess" />
    <OrderModal @register="orderDrawer[0]" @success="OrderModal" />

<!--    <Modal v-model:visible="applyViewShow" title="导入信息有误" @ok="applyViewClose">-->
<!--      <div>-->
<!--        <p v-for="(item, index) in msgList">{{ item.message }} </p>-->
<!--      </div>-->
<!--    </Modal>-->

  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  autoForecastCache2, productRemove, importDknProduct,forecastList,submitPlanData,saveForecastData,cleanForecastData
} from '@/api/heng/dkn';



import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  vxeTableColumns,
  vxeTableFormSchema,
} from './role.data';
import util from "@/utils/util";
import { reactive, ref, unref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { useMessage } from '@/hooks/web/useMessage';
import FormModal from "./FormModal.vue";
import OrderModal from "./OrderModal.vue";

import {useDrawer} from "@/components/Drawer";
import {VxeUI} from "vxe-pc-ui";

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

// const [register, { openModal, closeModal }] = useModal();
const loading = ref(false);
const visible = ref(false);
const applyViewShow = ref(false);

const totalObj = ref({ salesmanDeptList: [] })
const totalTitle = ref("");
const table_week_list = ref([]);
const editJson=ref({});//修改数据存储

const formValue=ref({dataSchema:''});

const [register, { openDrawer,closeDrawer }] = useDrawer();

const orderDrawer=useDrawer();

const currentWeek=ref("");//当前周

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    // showStatus: true,
    beforeEditMethod:(e)=>{
      return beforeEditFn(e);//beforeEditFn(e)
    }
  },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig: {},
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,

  },
  pagerConfig: {
    pageSize: 100,
  },
  expandConfig: {
    // labelField: 'modelCode',
    // padding : true,

    // childrenField: 'children',
  },
  treeConfig: { //张开配置
    // labelField: 'modelCode',
    childrenField: 'children',
  },
  proxyConfig: {
    props: {
      result: 'data.content',
      list: 'data.content',
      total: 'data.total',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      querySuccess:  (e)=>{
        let data = e.response.data;
        let weekMap=data.additionalPropeties.weekMap;
        // console.log("---e:",e);
        let week_list=[];
        // console.log("--weekMap.keys():", weekMap);
        for (const key in weekMap) {
          // console.log('键:', key);
          let f= insertString(key);
          let json={
            title: f,
            field: f,
            showOverflow: 'title',
            className: (({row, rowIndex, column, columnIndex, data}) => getRowClazzName(row, rowIndex, column, columnIndex, data)),
            // className: ((e) => getRowClazzName2(e)),
            editRender: {
              name: 'VxeNumberInput',
              events:{
                change: (e)=>{
                  inputChangeFn(e)
                }
              }
            },
            width:90,
            align: 'center',
          }
          week_list.push(json);
        }


        let last_obj={
          title: '小计',
          field: 'item_total',
          align: 'center',
          width:50,
          // type: "expand",
        }
        week_list.push(last_obj);
        table_week_list.value=week_list;


        currentWeek.value=week_list[0].field;

        let last= {
          width: 60,
          title: '操作',
          align: 'center',
          field: '',
          slots: { default: 'action' },
          fixed: 'right',
        };
        week_list.push(last);
        let arr=[...vxeTableColumns,...week_list];
        e.$grid.reloadColumn(arr);

        /**
         * 进行初始化运算
         */
        for (let i=0;i<data.content.length;i++){
          let item=data.content[i];
          if(item.children.length>3){
            try {
              forEachDeductionStock(currentWeek.value,item,"listInit")
            }catch(e){
              console.log(e);
              createMessage.error(e);
            }
          }

        }

        // console.log("--week_list:", week_list);
      }
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field ] = value;
    });
  }
  formValue.value = form;
  // console.log("----form:", form);
  // ywApproveList xftList
  return forecastList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const hasEditStatus = (row) => {
  const $grid = tableRef.value
  if ($grid) {
    return $grid.isEditByRow(row)
  }
}
// function getRowClazzName2(e){
//   let mto_arr="2835332，4124777，4528458，4850039";
//   // console.log(row);
//   // console.log(mto_arr.indexOf(row.itemCode)!=-1)
//   if(mto_arr.indexOf(e.row.itemCode)!=-1){
//     console.log("----e:",e);
//     //row-green
//     if(e.row.modelCode=="Project Stock"){
//
//       // console.log("- p-row:",row);
//       console.log("--rowIndex:",e.rowIndex)
//       let v= e.row[e.column.field];
//       console.log("--v:",v)
//     }
//   }
// }
function getRowClazzName(row, rowIndex, column, columnIndex, data){
  // console.log("----e:",row, rowIndex, $rowIndex, column, columnIndex, $columnIndex);
 // console.log("--column:",column);
  let clazzName="";

  //以下item_code不需要 判断负数  变红
  let mto_arr="2835332，4124777，4528458，4850039";
  // console.log(row);
  // console.log(mto_arr.indexOf(row.itemCode)!=-1)
  if(mto_arr.indexOf(row.itemCode)!=-1){
    //row-green
    if(row.modelCode=="Project Stock"){
      // console.log("- p-row:",row);
      // console.log("--rowIndex:",rowIndex)
      let v= row[column.field];
      let maxObj=row["Maximum Stock"];
      let max=maxObj[column.field];
      let minObj=row["Minimum Stock"];
      let min=minObj[column.field];
      if(v){
        if(v<min){
          clazzName="row-orange";
        }else if(v>min&&v<=max){
          clazzName="row-green";
        }else if(v>max){
          console.log("-v",v,":max-",max)
          clazzName="row-red";

        }
      }
    //  console.log("--v:",v)
    }
  }else{
    if(row.modelCode=="Project Stock"){
      let v= row[column.field];
      if(v&&v<0){
        clazzName="row-red";
      }
    }
  }

  return clazzName;
}


function formResetFn(data){

  editJson.value=ref({});
}

const saveRowEvent = (row) => {
  const $grid = tableRef.value
  if ($grid) {
    $grid.clearEdit().then(() => {
      gridOptions.loading = true
      setTimeout(() => {
        gridOptions.loading = false
      }, 300)
    })
  }
}

function getActions(record) {
  let arr = [
  ];
  if(hasEditStatus(record)){
    arr = [
      {
        // icon: 'clarity:note-edit-line',
        label: '保存',
        onClick: saveRowEvent.bind(null, record),
      }
    ];
  }

  return arr;
}

function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}

function openTiaoZheng(){
  console.log("editJson;",editJson.value);

  orderDrawer[1].openDrawer(true,editJson.value);
}

function submitBeforeFn(){
  VxeUI.modal.confirm({
    id:1,
    content: '确定提交计划!',
    // status: loading.value,
    lockView: false,
    mask: false,
    showClose: false,
    showConfirmButton: true
  }).then(type => {
    // console.log(`操作类型 ${type}`)
    if(type=="confirm"){
      submitPlanDataFn()
    }
  })
}


//提交计划
function submitPlanDataFn(){
  let tableData=tableRef.value?.getTableData().tableData;
  loading.value=true;
  submitPlanData(tableData).then(res=>{
    if(res.code==200){
      VxeUI.modal.close(1)
      createMessage.success(res.message);
      // tableRef.value?.commitProxy("reload");
    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value=false;
  })
}

function handleEdit(record: Recordable) {
  // openModal(true, {
  //   record
  // });
}

function handleClose(record: Recordable) {
  //console.log(record);

  productRemove(record)
    .then((res) => {
      if (res.code == 200) {
        createMessage.success(res.message);
        tableRef.value.commitProxy('reload');

      } else {
        createMessage.error(res.message);

      }

    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
    });
}




function handleSuccess() {
  tableRef.value.commitProxy('reload');
}


function insertString(str) {
  // 检查字符串长度是否至少有4位
  if (str.length < 4) {
    return str; // 长度不足4位则直接返回原字符串
  }
  // 在第4位后面插入'-W'
  return str.slice(0, 4) + '-W' + parseInt(str.slice(4));
}

/**
 * 校验哪些可编辑
 */
function beforeEditFn(e){
  let con=false;
  if(e.row.modelCode=="QTY Shipped Out"||e.row.modelCode=="New Planned DO (EPD)"||e.row.modelCode=="Updated Un-Finished Planned DO"){
    con=true;
  }
  return con;
}

/**
* 备货订单计算
*/
function inputChangeFn(e){
 // console.log("--inputChangeFn:",e);
  // console.log("--currentWeek:",currentWeek.value);
  let itemCode= e.row.itemCode;
  let modelCode= e.row.modelCode;


  let field= e.column.field;
  // console.log("--e.row:",e.row)
  // e.items;
  let value = e.row[field];
  let key=`${itemCode}:${field}`;
  if(!value){
    value=0;
  }
  if(value!=null) {

    let num = parseFloat(value);
    e.row[field] = num;

    try {
      //连续扣减
      forEachDeductionStock(field,e,"rowEdit")
    }catch(e){
      console.log(e);
      createMessage.error(e);
    }
   // console.log("---validated_num:",validated_num);


    if(modelCode=="New Planned DO (EPD)"){
      if(value>0){
        editJson.value[key]={field,value}
      }else{
        delete editJson.value[key];
      }
    }
  }else{

    if(modelCode=="New Planned DO (EPD)"){
      delete editJson.value[key];
    }

  }

}

/**
 * 循环扣减
 * field  当前要计算的周别字段 例如:2025-W43
 * e 表格change事件传入事件
 * last_result 上一个周别计算得出的理论库存
 * source:来源是单元格编辑’rowEdit‘ 还是 列表初始化时初步渲染运算 ’listInit‘；
 */
function forEachDeductionStock(field,e,source){

  if(field.indexOf("-W")!=-1){
// console.log("--source:",source)
    //预测汇总数据
    let validated_num=0;
    //查找当前库存
    let initialQuantity = 0;
    //已出库数量
    let yi_chu_num = 0;
    //未入库备货订单
    let wei_ru_num = 0;
    //调整的未入库备货订单
    let tz_wei_ru_num = 0;
    //新增备货订单计划
    let add_plan_num = 0;
    let project_stock_item=null;

    // console.log("---e.items:",e.items);
    let items=[];
    if(source=='rowEdit'){
      items=e.items;
    }
    if(source=='listInit'){
      items=e.children;
    }
    for (let a = 0; a < items.length; a++) {
      let a_item = items[a];

      //平台提供的字段
      if (a_item.modelCode == "Planned DO (EHD)"||a_item.modelCode == "Firmed DO (EHD)"||a_item.modelCode == "Validated DO (EHD)") {
        validated_num+=formatNumber(a_item[field]);
      }
      //新要求提供的字段
      if (a_item.modelCode == "Current Stock") {
        initialQuantity = a_item.initialQuantity;
      }
      //已出库数量
      if (a_item.modelCode == "QTY Shipped Out") {
        yi_chu_num = formatNumber(a_item[field]);
      }
      //未入库备货订单
      if (a_item.modelCode == "Un-Finished Planned DO (EPD)") {
        //  wei_ru_num = formatNumber(a_item[field]);
      }
      //调整的未入库备货订单数量
      if (a_item.modelCode == "Updated Un-Finished Planned DO") {
        tz_wei_ru_num = formatNumber(a_item[field]);
      }
      //新增备货订单计划
      if (a_item.modelCode == "New Planned DO (EPD)") {
        add_plan_num = formatNumber(a_item[field]);
      }
      if (a_item.modelCode == "Project Stock") {
        //上一周的理论库存
        project_stock_item = a_item;
      }
    }
    //求理论库存Project Stock
    /**
     * 1 是否本周
     */

    let project_stock_num = 0;
    if (currentWeek.value == field) {
      project_stock_num = util.copy(initialQuantity);
    } else {
      //获取上一周的理论库存
      let u_index = null;

      for (let i = 0; i < table_week_list.value.length; i++) {
        let item = table_week_list.value[i];

        if (item.field == field) {
          u_index = i - 1;
        }
      }
      if (u_index==null) {
        createMessage.error("-查找不到u_index field："+field)
        return;
      }
      let last_item = table_week_list.value[u_index];
      let last_field = last_item.field;
      for (let i = 0; i < items.length; i++) {
        let item = items[i];
        if (item.modelCode == "Project Stock") {
          //上一周的理论库存
          project_stock_num = formatNumber(item[last_field]);
          break;
        }
      }
    }

    //计算
    let result= yi_chu_num+wei_ru_num+tz_wei_ru_num+add_plan_num+project_stock_num-validated_num;
    // if(result>0){
    //   project_stock_item[field]=result;
    // }else{
    //   project_stock_item[field]=0;
    // }
    project_stock_item[field]=result;


    /**
     *  main 循环计算下一个周别
     */
      // if(result&&result>0){

    let next_index = null;
    for (let i = 0; i < table_week_list.value.length; i++) {
      let item = table_week_list.value[i];
      if (item.field == field&&(i + 1)<=table_week_list.value.length-1) {
        next_index = i + 1;
      }
    }
    if(next_index){

      let next_item = table_week_list.value[next_index];
      let next_field = next_item.field;
      let next_validated_num=0;
      for (let a = 0; a < items.length; a++) {
        let a_item = items[a];

        //平台提供的字段
        if (a_item.modelCode == "Planned DO (EHD)" || a_item.modelCode == "Firmed DO (EHD)" || a_item.modelCode == "Validated DO (EHD)") {
          next_validated_num += formatNumber(a_item[next_field]);
        }
      }
      // if(result-next_validated_num>0){
      //   forEachDeductionStock(next_field,e,source);
      // }
      forEachDeductionStock(next_field,e,source);
    }else{
      // createMessage.error("无法进行下一步计算")
      // return;
    }
  }


 // }


}



/**
 * 判断如果不是整数就进行四舍五入
 * @param num
 */
function formatNumber(num) {
  if(!num){
    return 0
  }
  num=parseFloat(num);
  return num;
  // // 判断是否为整数（利用取余运算）
  // if (num % 1 !== 0) {
  //   // 向下取整 不保留小数
  //   return Math.floor(num);
  // } else {
  //   // 整数直接返回（可根据需求转为数字或字符串）
  //   return num;
  // }
}

function upForecasFn(){
  loading.value=true;
  autoForecastCache2().then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      tableRef.value?.commitProxy("reload")
    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value=false;
  })
}

onMounted(()=>{
 //upForecasFn();
})

function saveForecastDataFn(){
  loading.value=true;
  let tableData=tableRef.value?.getTableData().tableData;
  saveForecastData(tableData).then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      tableRef.value?.commitProxy("reload")
    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value=false;
  })
}

function cleanForecastDataFn(){
  loading.value=true;

  cleanForecastData().then(res=>{
    if(res.code==200){
      createMessage.success(res.message);
      tableRef.value?.commitProxy("reload")
    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value=false;
  })
}

</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}
.row-red{
  color: red;
}
.row-green{
  color: green;
}
.row-orange{
  color: orange;
}
</style>
